package cn.net.isir.service2;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import cn.net.isir.common.ResultObject;
import cn.net.isir.utils.DateUtils;
import cn.net.isir.utils.StringUtils;
import cn.net.isir.core.BasicService2;
import cn.net.isir.core.SetBasicDao;
import cn.net.isir.dao.*;
import cn.net.isir.entity.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@Service
public class OrderService extends BasicService2<Order> {
    @SetBasicDao
    @Resource
    private OrderDao orderDao;
    @Resource
    private ShopDao shopDao;
    @Resource
    private OrderGoodsDao orderGoodsDao;
    @Resource
    private GoodsDao goodsDao;
    @Resource
    private GoodsSpecificationDao goodsSpecificationDao;
    @Resource
    private WxMinipUserinfoDao wxMinipUserinfoDao;
//    @Resource
//    private PrintTaskDao printTaskDao;

    @Resource
    private NotifyTaskService notifyTaskService;

    /**
     * 根据 订单编号 获取订单
     *
     * @param orderNo 订单编号
     * @return 订单信息
     */
    public Order selectByOrderNo(String orderNo) {
        return orderDao.selectByOrderNo(orderNo);
    }

    public ResultObject order(String edibleMethod, String shopid, String tableno, String userId, String client, String tastes, String goodsList, String formid) {
        ResultObject ro = new ResultObject();
        //菜品列表转换
        JSONArray goodsJSONArray;
        try {
            goodsJSONArray = JSONArray.parseArray(goodsList);
        } catch (Exception ex) {
            ro.setResult(500);
            ro.setMessage(ex.getMessage());
            ro.setObject(ex);
            return ro;
        }
        //订单编号中的用户类型：微信是W，支付宝是A
        String orderNoClientStr = null;
        //订单编号中的用户id
        String orderNoUserIdStr = null;
        //验证用户是否存在
        if ("wx".equals(client)) {
            WxMinipUserinfo wxMinipUserinfo = new WxMinipUserinfo();
            wxMinipUserinfo.setUnionid(userId);
            wxMinipUserinfo = wxMinipUserinfoDao.selectOne(wxMinipUserinfo);
            if (wxMinipUserinfo == null) {
                ro.setResult(500);
                ro.setMessage("用户不存在");
                return ro;
            }
            //设置id
            orderNoClientStr = "W";
            orderNoUserIdStr = wxMinipUserinfo.getId();
        }
        if ("alipay".equals(client)) {

            orderNoClientStr = "A";
            orderNoUserIdStr = "";
//            WxMinipUserinfo wxMinipUserinfo = new WxMinipUserinfo();
//            wxMinipUserinfo.setUnionid(unionid);
//            wxMinipUserinfo = wxMinipUserinfoDao.selectOne(wxMinipUserinfo);
//            if (wxMinipUserinfo == null) {
//                ro.setResult(500);
//                ro.setMessage("用户不存在");
//                return ro;
//            }
        }
        //查询订单
        Order order = new Order();
        //订单号生成规则：店铺ID+时间戳+用户ID
        order.setNo(orderNoClientStr + shopid + StringUtils.getCurrentTimeMillis() + orderNoUserIdStr);
        order.setShopId(shopid);
        //校验店铺是否存在
        Shop shop = shopDao.selectByPrimaryKey(shopid);
        if (shop == null) {
            ro.setResult(500);
            ro.setMessage("shop is not exist");
            return ro;
        }
        //桌号传递过来
        order.setSerialNumType(shop.getOrderStyle());
        if (shop.getOrderStyle().equals("table")) {
            order.setSerialNumber(tableno);
        }
        //流水号生成：四位数字随机生成----已废弃
//        if (shop.getOrderStyle().equals("serial")) {
//            Integer maxSerial = shop.getMaxSerial();
//            maxSerial = 9999;//最大9999
//
//            //查询本店订单信息
//            Order o = new Order();
//            o.setShopId(shopid);
//            o.setLimitHours(2);//本店铺两小时之内的所有订单
//            List<Order> shopOrderList = orderDao.selectList(o);
//            //随机数字
//            Random r = new Random();
//            Integer serialNumber;
//            //循环两个小时内的所有订单，如果没有重复的，则使用此随机流水号
//            boolean isExist;
//            do {
//                serialNumber = r.nextInt(maxSerial);
//                isExist = false;
//                for (Order so : shopOrderList) {
//                    if ("table".equals(so.getSerialNumType())) {
//                        continue;
//                    }
//                    if (String.valueOf(serialNumber).equals(so.getSerialNumber())) {
//                        isExist = true;
//                        break;
//                    }
//                }
//            } while (isExist);
//
//            order.setSerialNumber(String.valueOf(serialNumber));
//        }

        //流水号生成,一天内的流水号订单(从1开始排列)
        if (shop.getOrderStyle().equals("serial")) {
            //查询本店订单信息
            Order o = new Order();
            o.setShopId(shopid);
            //查询今天的所有订单
            o.setQueryStartOrderTime(new Date(DateUtils.getTodayZeroTimeInMillis()));
            List<Order> shopOrderList = orderDao.selectList(o);
            order.setSerialNumber(String.valueOf(shopOrderList.size() + 1));
        }
        //订单其他信息添加
        order.setOrderUser(userId);
        order.setClient(client);
//        order.setTotal();
//        order.setFinalTotal();
        order.setOrderStatus("ordered");
        order.setEdibleMethod(edibleMethod);//shop和takeaway
        order.setIsPaid(0);
        order.setIsInformShop(0);
        order.setIsServed(0);
        order.setIsFinished(0);
        order.setHasReturn(0);
        order.setOrderTime(new Date());
        order.setTaste(tastes);
        order.setCreateUser(userId);
        order.setComment(formid);

        BigDecimal total = BigDecimal.ZERO;
        List<OrderGoods> orderGoodsList = new ArrayList<>();
        //循环传回的每个菜
        for (Object o : goodsJSONArray) {
            JSONObject jo = JSONObject.parseObject(JSON.toJSONString(o));
            Object goodsido = String.valueOf(jo.get("goodsId"));
            Object quantityo = String.valueOf(jo.get("quantity"));
            Object specificationIdo = String.valueOf(jo.get("specId"));
            //查询参数是否传递
            if (goodsido == null || quantityo == null || specificationIdo == null) {
                ro.setResult(500);
                ro.setMessage("缺失菜品参数");
                return ro;
            }
            String goodid = String.valueOf(goodsido);
            Double quantity = Double.parseDouble(String.valueOf(quantityo));
            String specificationId = String.valueOf(specificationIdo);

            //查询菜品是否存在
            Goods goods = goodsDao.selectByPrimaryKey(goodid);
            if (goods == null) {
                ro.setResult(500);
                ro.setMessage("该菜品不存在");
                return ro;
            }

            //查询规格价格
            GoodsSpecification gs = new GoodsSpecification();
            gs.setId(specificationId);
            gs.setGoodsId(goods.getId());
            gs = goodsSpecificationDao.selectOne(gs);
            if (gs == null) {
                ro.setResult(500);
                ro.setMessage("该菜品规格不存在");
                return ro;
            }
            //订单菜品数据
            OrderGoods og = new OrderGoods();
//            og.setOrderId();
            og.setGoodsId(goodid);
            og.setName(goods.getName());
            og.setSpecName(gs.getName());
            if (gs.getFee() == null) {
                gs.setFee(gs.getFinalFee());
            }
            og.setFee(gs.getFee().multiply(new BigDecimal(quantity)));
            og.setFinalFee(gs.getFinalFee().multiply(new BigDecimal(quantity)));
            og.setSpecifications(gs.getId());
            og.setNum(String.valueOf(quantity));
            og.setCreateUser(userId);
            orderGoodsList.add(og);
            //累计价格
            total = total.add(og.getFinalFee());
        }
        order.setTotal(total);
        order.setFinalTotal(total);
        //新建订单
        orderDao.insert(order);
        for (OrderGoods og : orderGoodsList) {
            og.setOrderId(order.getId());
            orderGoodsDao.insert(og);
        }
        ro.setResult(200);
        ro.setMessage("success");
        //返回订单主键
        ro.setObject(order.getId());
        return ro;
    }

    /**
     * 查询订单的历史数据
     *
     * @param userId     用户id
     * @param client     用户类型：wx或alipay
     * @param shopid     店铺id
     * @param limitHours 查询几小时之内的订单
     * @return 订单列表
     */
    public ResultObject orderHistory(String userId, String client, String shopid, Integer limitHours) {
        //声明返回值
        ResultObject ro = new ResultObject();
        Order order = new Order();
        order.setShopId(shopid);
        order.setOrderUser(userId);
        order.setClient(client);
        if (limitHours != null) {
            order.setLimitHours(limitHours);//3小时之内创建的订单
        }
        List<Order> orderList = orderDao.selectList(order);
        if (orderList == null || orderList.size() == 0) {
            ro.setResult(200);
            ro.setObject(orderList);
            return ro;
        }
        List<JSONObject> orderJSONList = new ArrayList<>();
        for (Order o : orderList) {
            JSONObject jo = new JSONObject();//.parseObject(o.toString());
            jo.put("orderno", o.getNo());
            jo.put("ordertime", o.getOrderTime());
            jo.put("type", o.getSerialNumType());
            jo.put("serialNumber", o.getSerialNumber());
            jo.put("tastes", o.getTaste());
            jo.put("fee", o.getFinalTotal());
            jo.put("edibleMethod", o.getEdibleMethod());
            OrderGoods orderGoods = new OrderGoods();
            orderGoods.setOrderId(o.getId());
            JSONArray jsonArray = new JSONArray();
            List<OrderGoods> orderGoodsList = orderGoodsDao.selectList(orderGoods);
            if (orderGoodsList != null && orderGoodsList.size() != 0) {
                for (OrderGoods og : orderGoodsList) {
                    JSONObject jog = new JSONObject();
                    jog.put("goodsName", og.getName());
                    jog.put("specName", og.getSpecName());
                    jog.put("specFee", og.getFinalFee());
                    jog.put("quantity", og.getNum());
                    jsonArray.add(jog);
                }
                jo.put("orderGoods", jsonArray);
            }
            orderJSONList.add(jo);
        }
        ro.setResult(200);
        ro.setMessage("success");
        ro.setObject(orderJSONList);
        return ro;
    }

    /**
     * 支付完成后的处理方法，包含：更改订单状态，发送打印通知。
     *
     * @param orderNo  订单no
     * @param paidUser 付款人
     * @return 处理结果
     */
    public boolean paidOrderHandle(String orderNo, String paidUser, String payment, String client) {
        try {
            //查询订单信息
            Order order = new Order();
            order.setNo(orderNo);
            order = orderDao.selectOne(order);
            if (order == null || order.getIsInformShop() == 1) {
                return false;
            }
            //查询店铺信息
            Shop shop = shopDao.selectByPrimaryKey(order.getShopId());
            if (shop == null) {
                return false;
            }

            //FIXME 通知店铺打印机服务

            //打印任务表里,新增打印任务
//            PrintTask printTask = new PrintTask();
//            printTask.setShopId(order.getShopId());
//            printTask.setOrderNo(order.getNo());
//            printTask.setOperator(order.getOrderUser());
//            printTask.setAddress(shop.getAddress());
//            printTask.setTel(shop.getTel());
//            printTask.setStatus("paid");//未通知
//            printTaskDao.insert(printTask);

            NotifyTask nt = new NotifyTask();
            nt.setShopId(order.getShopId());
            nt.setOrderNo(order.getNo());
            nt.setOperator(order.getOrderUser());
            nt.setAddress(shop.getAddress());
            nt.setTel(shop.getTel());
            nt.setOtherInfo(null);
            nt.setPrintStatus("paid");
            nt.setPrintTime(null);
            nt.setPlatformStatus("paid");
            nt.setPlatformTime(null);
            nt.setOther1Status("paid");
            nt.setOther1Time(null);
            nt.setOther2Status("paid");
            nt.setOther2Time(null);
            nt.setOther3Status("paid");
            nt.setOther3Time(null);
            nt.setOther4Status("paid");
            nt.setOther4Time(null);
            nt.setOther5Status("paid");
            nt.setOther5Time(null);
            nt.setOther6Status("paid");
            nt.setOther6Time(null);
            nt.setOther7Status("paid");
            nt.setOther7Time(null);
            nt.setComment(order.getComment());
            notifyTaskService.insert(nt);

//        xxxService.notify(orderid);
            //更改订单状态
            order.setOrderStatus("paid");//订单状态
            order.setOrderUser(paidUser);//支付人
            order.setPayTime(new Date());//支付日期
            order.setPayment(payment);//支付方式
            order.setIsPaid(1);//已支付
            order.setIsInformShop(1);//是否已通知店铺
            order.setStatus("paid");//订单状态
            orderDao.update(order);
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 根据用户id获取订单列表
     *
     * @param userId 用户id
     * @return 列表
     */
    public List<Order> selectListByUser(String userId) {
        return orderDao.selectListByUser(userId);
    }
}
